package com.sh.粘包半粘包.three;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.ByteBuffer;

public class TcpClient {
    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("localhost", 8888);
        OutputStream outputStream = socket.getOutputStream();

        String message1 = "Hello";
        byte[] message1Bytes = message1.getBytes();
        byte[] message1LengthBuffer = ByteBuffer.allocate(4).putInt(message1Bytes.length).array();
        outputStream.write(message1LengthBuffer);
        outputStream.write(message1Bytes);
        outputStream.write(message1LengthBuffer);
        outputStream.write(message1Bytes);
        outputStream.write(message1LengthBuffer);
        outputStream.write(message1Bytes);
        outputStream.write(message1LengthBuffer);
        outputStream.write(message1Bytes);

        String message2 = "World";
        byte[] message2Bytes = message2.getBytes();
                                                // 加上一个表示消息长度的 4 字节整数
        byte[] message2LengthBuffer = ByteBuffer.allocate(4).putInt(message2Bytes.length).array();
        outputStream.write(message2LengthBuffer);
        outputStream.write(message2Bytes);
        outputStream.write(message2LengthBuffer);
        outputStream.write(message2Bytes);
        outputStream.write(message2LengthBuffer);
        outputStream.write(message2Bytes);
        outputStream.write(message2LengthBuffer);
        outputStream.write(message2Bytes);

        socket.close();
    }
}